package org.springframework.jdbc.core.namedparam;

import java.util.List;
import com.gitee.qdbp.jdbc.api.SqlBoot;
import com.gitee.qdbp.jdbc.sql.SqlBuffer;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * 解析名称参数, 生成SqlBuffer<br>
 * ParsedSql中的getOriginalSql,getParameterNames不是public方法, 只好写在这个package中
 *
 * @author zhaohuihua
 * @version 20201208
 */
public class NamedParameterTools {

    private final SqlBoot sqlBoot;

    public NamedParameterTools(SqlBoot sqlBoot) {
        this.sqlBoot = sqlBoot;
    }

    public SqlBuffer buildSqlBuffer(String sql, SqlParameterSource paramSource) {
        VerifyTools.requireNotBlank(sql, "sql");
        ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
        String originalSql = parsedSql.getOriginalSql();
        List<String> paramNames = parsedSql.getParameterNames();
        if (paramNames.isEmpty()) {
            return sqlBoot.newSqlBuffer().append(originalSql);
        }
        SqlBuffer actualSql = sqlBoot.newSqlBuffer();
        int lastIndex = 0;
        for (int i = 0; i < paramNames.size(); i++) {
            String paramName = paramNames.get(i);
            int[] indexes = parsedSql.getParameterIndexes(i);
            int startIndex = indexes[0];
            int endIndex = indexes[1];
            actualSql.append(originalSql.substring(lastIndex, startIndex));
            if (paramSource != null && paramSource.hasValue(paramName)) {
                Object value = paramSource.getValue(paramName);
                actualSql.addVariable(value);
            } else {
                actualSql.addVariable(null);
            }
            lastIndex = endIndex;
        }
        actualSql.append(originalSql.substring(lastIndex));
        return actualSql;
    }
}
